package dev.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

	/**
	 * 添加cookie
	 * 
	 * @author chenjy
	 * @time 2017年11月12日 下午3:16:01
	 * @param response
	 * @param name
	 *            cookie 名称
	 * @param value
	 *            cookie 值
	 * @param maxAge
	 *            cookie 存储时间
	 * @description
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value,
                                 int maxAge) {
		Cookie cookie = new Cookie(name, value);
		String path = request.getContextPath();
		cookie.setPath(path); // 只将cookie保存为当前项目下
		if (maxAge > 0)
			cookie.setMaxAge(maxAge);
		response.addCookie(cookie);
	}
	
	public static void removeCookie(HttpServletRequest request, HttpServletResponse response,String name) {
		addCookie(request, response, name, "", 0);
	}

	/**
	 * 根据cookie名称获取cookie对象
	 * 
	 * @author chenjy
	 * @time 2017年11月12日 下午3:22:15
	 * @param request
	 * @param name
	 *            cookie名称
	 * @return
	 * @description
	 */
	public static Cookie getCookieByName(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies.length == 0)
			return null;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(name))
				return cookie;
		}
		return null;
	}
}
